<template>
  <div class="calibration-container">
    <!-- 顶部控制区域 -->
    <div class="top-controls">
      <div class="control-group">
        <span class="control-label">预测管道</span>
        <el-select
          v-model="predictPipeline"
          placeholder="请选择预测管道"
          class="control-select"
          clearable
        >
          <el-option
            v-for="item in pipelineList"
            :key="item.id"
            :label="item.value"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="control-group">
        <span class="control-label">校准起始日期</span>
        <el-date-picker
          v-model="startTime"
          type="date"
          placeholder="请选择起始日期"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
          class="control-date-picker"
          clearable
        />
      </div>
      <div class="control-group">
        <span class="control-label">校准结束日期</span>
        <el-date-picker
          v-model="endTime"
          type="date"
          placeholder="请选择结束日期"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
          class="control-date-picker"
          clearable
        />
      </div>
    </div>

    <!-- 图表类型切换按钮 -->
    <div class="chart-type-controls">
      <el-button
        :type="chartType === 'temperature' ? 'primary' : 'default'"
        @click="switchChartType('temperature')"
        class="chart-type-btn"
        size="large"
      >
        温度校准结果
      </el-button>
      <el-button
        :type="chartType === 'pressure' ? 'primary' : 'default'"
        @click="switchChartType('pressure')"
        class="chart-type-btn"
        size="large"
      >
        压力校准结果
      </el-button>
    </div>

    <!-- 图表容器 -->
    <div class="chart-container">
      <div v-if="isCalibrating" class="chart-loading-overlay">
        <el-icon class="loading-icon is-loading" size="48" color="#385e8e">
          <Loading />
        </el-icon>
        <p class="loading-text">校准结果加载中...</p>
      </div>
      <v-chart
        v-if="currentChartOption && isCalibrated"
        ref="chartRef"
        :option="currentChartOption"
        class="chart-instance"
        autoresize
      />
      <div v-else class="chart-placeholder">
        <div class="placeholder-content">
          <el-icon class="placeholder-icon" size="48" color="black">
            <TrendCharts />
          </el-icon>
          <p class="text-black placeholder-text">请选择参数并点击开始校准查看图表</p>
        </div>
      </div>
    </div>

    <!-- 右侧按钮 -->
    <div class="action-buttons">
      <el-button
        type="primary"
        size="large"
        :loading="isCalibrating"
        @click="handleStartCalibration"
      >
        {{ isCalibrating ? '校准中...' : '开始校准' }}
      </el-button>
      <el-button type="primary" size="large" :disabled="!isCalibrated" @click="handleExportChart">
        导出图表
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { createTemperatureOption, createPressureOption } from './chart-options'
import { ElMessage } from 'element-plus'
import { TrendCharts, Loading } from '@element-plus/icons-vue'
import { useSimulationStore } from '@/stores/modules/simulation'
import {
  getWBXJIAOZHUN,
  getBKXJIAOZHUN,
  getDYYXJIAOZHUN,
  getS81XJIAOZHUN
} from '@/api/parameter_calibration'

// 注册 ECharts 组件
use([CanvasRenderer, LineChart, TitleComponent, TooltipComponent, LegendComponent, GridComponent])
const simulationStore = useSimulationStore()
// 响应式数据
const startTime = ref('')
const endTime = ref('')
const chartType = ref('temperature') // 'temperature' 或 'pressure'
const predictPipeline = ref('')
const isCalibrating = ref(false) // 校准状态
const isCalibrated = ref(false) // 是否已校准
const chartRef = ref(null) // 图表引用

const temperatureOption = ref(createTemperatureOption())
const pressureOption = ref(createPressureOption())

const PIPELINE_API_MAP = {
  '乌-百线': getWBXJIAOZHUN,
  '百-克线': getBKXJIAOZHUN,
  '81#-701线': getS81XJIAOZHUN,
  '701-总站线': getDYYXJIAOZHUN
}

const pipelineList = ref([
  { id: 1, value: '乌-百线' },
  { id: 2, value: '百-克线' },
  { id: 3, value: '81#-701线' },
  { id: 4, value: '701-总站线' }
])

// 计算当前图表配置
const currentChartOption = computed(() =>
  chartType.value === 'temperature' ? temperatureOption.value : pressureOption.value
)

const formatDateParam = (value) => (value ? value.replace(/-/g, '') : '')

const resetChartOptions = () => {
  temperatureOption.value = createTemperatureOption()
  pressureOption.value = createPressureOption()
}

const updateChartOptions = (records) => {
  const timestamps = records.map((item) => item.time)

  temperatureOption.value = createTemperatureOption(
    timestamps,
    records.map((item) => item.final_station_inlet_temperature_calibration_value ?? null),
    records.map((item) => item.final_station_inlet_temperature_actual_measurement_value ?? null)
  )

  pressureOption.value = createPressureOption(
    timestamps,
    records.map((item) => item.first_station_outlet_pressure_calibration_value ?? null),
    records.map((item) => item.first_station_outlet_pressure_actual_measurement_value ?? null)
  )
}

// 切换图表类型
const switchChartType = (type) => {
  chartType.value = type
}

// 开始校准函数
const handleStartCalibration = async () => {
  if (!startTime.value || !endTime.value) {
    ElMessage.warning('请先选择校准起始日期和结束日期')
    return
  }

  if (!predictPipeline.value) {
    ElMessage.warning('请先选择预测管道')
    return
  }

  if (new Date(startTime.value) >= new Date(endTime.value)) {
    ElMessage.warning('起始日期不能晚于或等于结束日期')
    return
  }

  const apiFn = PIPELINE_API_MAP[predictPipeline.value]
  if (!apiFn) {
    resetChartOptions()
    ElMessage.warning('当前管道暂不支持在线校准')
    return
  }

  isCalibrated.value = false
  isCalibrating.value = true

  const payload = {
    start_date: formatDateParam(startTime.value),
    end_date: formatDateParam(endTime.value)
  }

  try {
    const response = await apiFn(payload)
    const records = response?.data?.parameter_calibration ?? []

    if (predictPipeline.value === '乌-百线') {
      simulationStore.ruf_wbx = response?.data?.roughness
      simulationStore.K_G_wbx = response?.data?.soil_thermal_conductivity
      simulationStore.K_F_wbx = response?.data?.insulation_layer_thermal_conductivity
    } else if (predictPipeline.value === '百-克线') {
      simulationStore.ruf_bkx = response?.data?.roughness
      simulationStore.K_G_bkx = response?.data?.soil_thermal_conductivity
    } else if (predictPipeline.value === '81#-701线') {
      simulationStore.ruf_81x = response?.data?.roughness
      simulationStore.K_G_81x = response?.data?.soil_thermal_conductivity
    } else if (predictPipeline.value === '701-总站线') {
      simulationStore.ruf_dyyx = response?.data?.roughness
      simulationStore.K_G_dyyx = response?.data?.soil_thermal_conductivity
    }

    if (!records.length) {
      resetChartOptions()
      ElMessage.warning('未获取到校准结果，请调整时间范围后再试')
      return
    }

    updateChartOptions(records)
    isCalibrated.value = true
    ElMessage.success('校准完成，图表已更新')
  } catch (error) {
    resetChartOptions()
    ElMessage.error('校准失败，请稍后重试')
    console.error('Calibration error:', error)
  } finally {
    isCalibrating.value = false
  }
}

// 导出图表
const handleExportChart = async () => {
  if (!isCalibrated.value) {
    ElMessage.warning('请先完成校准')
    return
  }

  if (!chartRef.value) {
    ElMessage.warning('图表未加载完成')
    return
  }

  try {
    // 调试信息
    console.log('ChartRef value:', chartRef.value)
    console.log('ChartRef methods:', Object.getOwnPropertyNames(chartRef.value))

    const chartInstance = chartRef.value.chart

    // 导出为图片
    const dataUrl = chartInstance.getDataURL({
      type: 'png',
      pixelRatio: 2,
      backgroundColor: '#fff'
    })

    // 创建下载链接
    const link = document.createElement('a')
    const fileName = `${chartType.value === 'temperature' ? '温度' : '压力'}校准图表_${new Date().getTime()}.png`
    link.download = fileName
    link.href = dataUrl

    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    ElMessage.success('图表导出成功！')
  } catch (error) {
    ElMessage.error('导出失败，尝试备选方案')
    console.error('Export error:', error)
    // 备选方案
    await exportChartAsScreenshot()
  }
}
</script>

<style lang="scss" scoped>
.calibration-container {
  position: relative;
  width: 100%;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.top-controls {
  position: absolute;
  top: 20px;
  right: 20px;
  display: flex;
  align-items: center;
  gap: 24px;
  background: rgba(255, 255, 255, 0.9);
  padding: 16px 24px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.control-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.control-label {
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
  white-space: nowrap;
}

.control-select {
  width: 180px;
}

.control-date-picker {
  width: 180px;
}

.chart-type-controls {
  position: absolute;
  top: 100px;
  left: 20px;
  display: flex;
  gap: 16px;
  z-index: 10;
}

.chart-type-btn {
  min-width: 140px;
  font-weight: 600;
  border-radius: 8px;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}

.chart-title-hint {
  position: absolute;
  top: 160px;
  left: 20px;
  z-index: 10;
}

.hint-text {
  font-size: 16px;
  font-weight: 600;
  color: #e74c3c;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
}

.chart-container {
  position: absolute;
  top: 200px;
  left: 20px;
  right: 20px;
  bottom: 140px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.chart-loading-overlay {
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  background: rgba(255, 255, 255, 0.85);
  z-index: 20;
}

.chart-instance {
  width: 100%;
  height: 100%;
}

.chart-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  // background: rgba(0, 0, 0, 0.2);
  color: white;
}

.placeholder-content {
  text-align: center;
}

.placeholder-icon {
  margin-bottom: 16px;
  opacity: 0.8;
}

.placeholder-text {
  font-size: 18px;
  font-weight: 500;
  margin: 0;
  opacity: 0.9;
}

.loading-text {
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
}

.action-buttons {
  position: absolute;
  right: 20px;
  bottom: 20px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

// 响应式设计
@media (max-width: 1200px) {
  .top-controls {
    flex-direction: column;
    gap: 12px;
    right: 10px;
    top: 10px;
  }

  .chart-type-controls {
    top: 140px;
    left: 10px;
  }

  .chart-title-hint {
    top: 200px;
    left: 10px;
  }

  .chart-container {
    top: 240px;
    left: 10px;
    right: 10px;
  }
}

:deep(.el-button + .el-button) {
  margin-left: 0;
}
</style>
